/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import java.util.ArrayList;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.UTSCheduleApp;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.ui.InputDialogFragment;
import utsc.apps.utschedule.ui.InputDialogFragment.OnInputListener;
import utsc.apps.utschedule.ui.MessageDialogFragment;
import utsc.apps.utschedule.ui.interfaces.OnSyncListener;
import utsc.apps.utschedule.util.AppUtils;
import utsc.apps.utschedule.util.TimetableHelper;
import utsc.apps.utschedule.util.Validator;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.actionbarsherlock.view.MenuItem;

/**
 * This is the activity used to perform the login process to UTSC Intranet. 
 *
 */
public class LoginActivity extends GenericFragmentActivity implements OnClickListener,OnSyncListener<Course>,OnInputListener{

	private static final String TAG="utsc.apps.utschedule.ui.activities.LoginActivity";
	private EditText _txtUserid;
	private EditText _txtPassword;
	private String _userid;
	private String _password;
	private Button _btnLogin;
	private final Validator _validator=Validator.newInstance(TAG);
	private boolean _fromSetting=false;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		Intent requestIntent=getIntent();
		if (requestIntent!=null) {
			_fromSetting=requestIntent.getBooleanExtra("setLogin", false);
		}
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.activity_login);
		//setup the necessary resources
		_txtUserid=(EditText) findViewById(R.id.frm_txt_userid);
		_txtPassword=(EditText) findViewById(R.id.frm_txt_password);
		_btnLogin=(Button) findViewById(R.id.btn_login);
		_btnLogin.setOnClickListener(this);
		
		//check whether or not it was opened from the setting page
		if (_fromSetting) {
			String[] loginSettings=AppUtils.getLoginPreferences(this);
			//if from setting, pre-fill the data
			if (loginSettings!=null) {
				_userid=loginSettings[0];
				_password=loginSettings[1];
				_txtUserid.setText(_userid);
				_txtPassword.setText(_password);
				_btnLogin.setText("Ok");
			}
		}
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			Toast.makeText(this, "Sync is cancelled.", Toast.LENGTH_SHORT).show();
			finish();
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onSyncCompleted(ArrayList<Course> result) {
		//if sync is completed and got the desired result
		if (result!=null&&!result.isEmpty()) {
			//save the user id and pw into our private protected login preference
			AppUtils.saveLoginPreferences(this, _userid, _password);
			if (_fromSetting) {
				UTSCheduleApp app=(UTSCheduleApp)getApplication();
				Timetable timetable=app.get_currentActiveTimetable();
				if (timetable!=null) {
					DatabaseManager.getInstance(this).resetTimetable(timetable);
					DatabaseManager.getInstance(this).saveSyncCourse(timetable.get_timetableID(),result);
					app.refreshCurrentTimetable();
					timetable.refreshCourseList();
				}
				Toast.makeText(this, "Login setting is updated.", Toast.LENGTH_LONG).show();
			}else {
				((UTSCheduleApp)getApplication()).set_syncedCourses(result);
				setResult(RESULT_OK);
				Toast.makeText(this, "Sync is completed.", Toast.LENGTH_SHORT).show();
			}
			
			finish();
		}
		//otherwise, show an error message to indicate the sync is failed 
		else {
			UTSCheduleApp app=(UTSCheduleApp)getApplication();
			Timetable timetable=app.get_currentActiveTimetable();
			if (timetable!=null) {
				app.refreshCurrentTimetable();
				timetable.refreshCourseList();
			}
			showDialogFragment(MessageDialogFragment.newInstance("Error - Sync", "We are unable to sync your courses. It could be related to login account or your intranet profile. Please try again later."), MessageDialogFragment.TAG);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//make sure the user id and pw are clear before exit
		if (isFinishing()) {
			_userid=null;
			_password=null;
		}
	}
	
	@Override
	public void onClick(View v) {
		//on login button clicked
		//validate all the inputs before proceeding further
		_userid=_txtUserid.getText().toString();
		_password=_txtPassword.getText().toString();
		_validator.reset();
		_validator.checkNull(_userid, "User Name cannot be empty!");
		_validator.checkNull(_password, "Password cannot be empty!");
		if (_validator.get_errorMessages()!=null) {
			showDialogFragment(MessageDialogFragment.newInstance("Error - Login", _validator.get_errorMessages()), MessageDialogFragment.TAG);
		}else {
			if (_fromSetting) {
				showDialogFragment(InputDialogFragment.newInstance("Warning", "Changing the account setting will cause an overwrite of your current timetable.\nAre you sure you want to proceed?", "Yes","No"), InputDialogFragment.TAG);
			}else {
				new SyncCourseTask(this, TimetableHelper.getCurrentTermString()).execute(_userid,_password);
			}
		}
	}

	@Override
	public void setupInputs(View v) {}

	@Override
	public void onInputSaveListener(View v) {
		Timetable timetable=((UTSCheduleApp)getApplication()).get_currentActiveTimetable();
		if (timetable!=null) {
			new SyncCourseTask(this, TimetableHelper.getCurrentTermString()).execute(_userid,_password);
		}
	}
}
